// Created by lifei on 2020/6/2--15:23.
import request from "@/plugins/axios";
import store from "~/store/index";
import { Message } from "element-ui";

// 下载资源
export const downloadBlob = (data, fileName) => {
	let blob = new Blob([data]);
	if ("download" in document.createElement("a")) {
		// 不是IE浏览器
		let url = window.URL.createObjectURL(blob);
		let link = document.createElement("a");
		link.style.display = "none";
		link.href = url;
		link.setAttribute("download", fileName);
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link); // 下载完成移除元素
		window.URL.revokeObjectURL(url); // 释放掉blob对象
	} else {
		// IE 10+
		window.navigator.msSaveBlob(blob, fileName);
	}
};

// 获取图片地址
export const getPic = url => {
	return new Promise((resolve, reject) => {
		request({
			url: url,
			method: "get",
			responseType: "blob"
		})
			.then(resp => {
				resolve(window.URL.createObjectURL(resp.data));
			})
			.catch(() => {
				resolve("");
			});
	});
};

/**
 * 根据字典名称获取字典项
 * @param {String} typeName
 */
export const getDict = function(typeName) {
	let data = store.state.dict.find(item => item.type === typeName) || {};
	return data.children || [];
};

/**
 * 带上请选择返回字典列表
 * @param {String} typeName 字典键名
 */
export const getDictAndPlease = function(typeName) {
	let data = store.state.dict.find(item => item.type === typeName) || {};
	// let please = {
	//     label: "-=请选择=-",
	//     value: -1
	// }

	let tempData = data.children.concat();

	/*if((tempData != undefined || tempData != null || tempData.length != 0) && tempData[0].value != '-1'){
        tempData.unshift(please)
    }*/

	return tempData || [];
};

/**
 * 根据权限键名获取权限
 * @param {String} key 权限键名
 */
export const getPermissions = key => {
	const roles = store.state.user.roles || {};
	return roles[key] || false;
};

/**
 * 处理可编辑表格校验
 * @param data
 * @param editTableRules
 * @returns {Promise<unknown>}
 */
export function validateEditTable(data, editTableRules) {
	return new Promise((resolve, reject) => {
		let msg = "";
		Object.keys(data).map((key, index) => {
			editTableRules.map(rules => {
				if (rules.attribute === key) {
					if (data[key] instanceof Array) {
						if (data[key].length > 0) {
							for (let i = 0; i < data[key].length; i++) {
								if (
									data[key][i] === "" ||
									data[key][i] === null ||
									data[key][i] === undefined
								) {
									msg += `<p>${rules.label}不能为空！</p>`;
									break;
								}
							}
						} else {
							msg += `<p>${rules.label}不能为空！</p>`;
						}
					} else if (
						data[key] === "" ||
						data[key] === null ||
						data[key] === undefined
					) {
						msg += `<p>${rules.label}不能为空！</p>`;
					}
				}
			});
		});
		setTimeout(function() {
			if (msg.length > 0) {
				console.log("11", data);
				Message.error({ dangerouslyUseHTMLString: true, message: msg });
				resolve(false);
			} else {
				resolve(true);
			}
		}, 100);
	});
}

/**
 * 格式化金额，整数的话直接返回，不是整数返回两位小数
 * @param {String|Number} num 金额
 */
export const formatMoney = num => {
	let newNum = typeof num === "number" ? num : Number(num);
	return String(newNum).indexOf(".") > 0 ? newNum.toFixed(2) : newNum;
};

/**
 * 属性赋值
 * @param target 目标对象
 * @param source 源对象
 */
export function setProperty(target, source) {
	for (let i of Object.keys(target)) {
		target[i] = source[i];
	}
	return target;
}

export default {
	getDict,
	validateEditTable
};
